JSON com Python


Aprender a usar JSON com Python e com o pacote pandas.


In [4]:
# Importando os módulos necessários
import numpy as np
from pandas import Series, DataFrame
import pandas as pd
import json

In [3]:
# Exemplo de um objeto JSON (JavaScript Object Notation):
json_obj = """
{   "zoo_animal": "Lion",
    "food": ["Meat", "Veggies", "Honey"],
    "fur": "Golden",
    "clothes": null, 
    "diet": [{"zoo_animal": "Gazelle", "food":"grass", "fur": "Brown"}]
}
"""

In [5]:
data = json.loads(json_obj)

In [6]:
data


Out[6]:
{'clothes': None,
 'diet': [{'food': 'grass', 'fur': 'Brown', 'zoo_animal': 'Gazelle'}],
 'food': ['Meat', 'Veggies', 'Honey'],
 'fur': 'Golden',
 'zoo_animal': 'Lion'}

In [7]:
# para converter o objeto para json novamente usamos o método dump do mudulo json
json.dumps(data)


Out[7]:
'{"zoo_animal": "Lion", "diet": [{"zoo_animal": "Gazelle", "food": "grass", "fur": "Brown"}], "clothes": null, "food": ["Meat", "Veggies", "Honey"], "fur": "Golden"}'

In [8]:
dframe = DataFrame(data['diet'])

In [9]:
dframe


Out[9]:
food fur zoo_animal
0 grass Brown Gazelle

In [ ]: